const path = require('path')
const mkdirp = require('mkdirp')
const moment = require('moment')

const _ = require('lodash')

const Response = require('../response')


function createDB(path) {
    const db = require('better-sqlite3')(path)
    db.exec(`
        CREATE TABLE IF NOT EXISTS cache (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            key VARCHAR(256) UNIQUE,
            value TEXT,
            ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        );
    `)

    return db
}

module.exports = ({cacheSeconds, fileCacheDir}) => {
    if (cacheSeconds <= 0) {
        return {
            get(){},
            set(){},
        }
    }

    mkdirp(fileCacheDir)
    db = createDB(path.join(fileCacheDir, 'cache.sqlite'))

    selectStmt = db.prepare('SELECT value FROM cache WHERE key = ? AND ts >= ?')
    insertStmt = db.prepare('REPLACE INTO cache(key, value, ts) VALUES (?, ?, ?)')

    return {
        get(request) {
            const sec = _.defaultTo(request.cacheSeconds, cacheSeconds)
            if (sec < 60) {
                return undefined
            }

            const ts = moment().format('X') - sec
            const dt = moment(ts * 1000).format('YYYY-MM-DD HH:mm:ss')
            const row = selectStmt.get(request.url, dt)
            if (_.isUndefined(row)) {
                return undefined
            }
            const response = Response.deserialize(request, row.value)
            return response
        },

        set(request, response) {
            if (!_.defaultTo(request.writeCache, true)) {
                return
            }

            const s = response.serialize()
            insertStmt.run(request.url, s, moment().format('YYYY-MM-DD HH:mm:ss'))
        }
    }
}